
package com.ifcar.app.adapter;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ifcar.app.model.Vote;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.MyGallery;
import com.ifcar.app.activity.R;

public class VoteAdapter extends HeadlineAdapter {

    private LayoutInflater mInflater;

    private VoteViewBinder mViewBinder;

    private OnClickListener mOnClickListener;
    
    private ThemeSettingsHelper mThemeSettingsHelper;

    public VoteAdapter(Context context, List<Map<String, Object>> list, OnClickListener l) {
        super(context, list);
        mInflater = LayoutInflater.from(context);
        mOnClickListener = l;
        mThemeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(context);

    }

    @Override
    public int getCount() {
        return getRealCount();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewparent) {
        position = getRealPosition(position);
        if (getRealCount() == 0) {
            return null;
        }

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.vote_item, viewparent, false);
        }

        Map<String, Object> data = (Map<String, Object>) getItem(position);

        View voteItem = convertView.findViewById(R.id.vote_item);
        View voteSubmit = convertView.findViewById(R.id.vote_submit);
        View voteSee = convertView.findViewById(R.id.vote_see);

        boolean isOver = position != 0;
        // 如果是往期投票没有是否已投票信息
        boolean isVoted = isOver ? false : Vote.isVoted(getContext(), data);

        // 绑定投票信息
        if (mViewBinder != null) {
            mViewBinder.bindView(voteItem, data, isVoted, isOver, mOnClickListener);
        }
        
        View digestContainer = voteItem.findViewById(R.id.digest_container);
        digestContainer.setPadding(digestContainer.getPaddingLeft(),
                digestContainer.getPaddingTop() * 3, digestContainer.getPaddingRight(),
                digestContainer.getPaddingBottom() * 3);

        // 如果已经投过,绑定查看投票,否则绑定投票
        if (!isOver && !isVoted) {
            if (voteSubmit == null) {
                FrameLayout extraContainer = (FrameLayout) voteItem
                        .findViewById(R.id.vote_item_extra);
                voteSubmit = mInflater.inflate(R.layout.vote_item_submit, extraContainer, false);
                extraContainer.addView(voteSubmit);
            }
            voteSubmit.setVisibility(View.VISIBLE);
            if (voteSee != null) {
                voteSee.setVisibility(View.GONE);
            }
            bindVoteSubmitView((ViewGroup) voteSubmit.findViewById(R.id.vote_submit_container),
                    data, ((MyGallery) viewparent).inLayout());
        } else {
            if (voteSee == null) {
                FrameLayout extraContainer = (FrameLayout) voteItem
                        .findViewById(R.id.vote_item_extra);
                voteSee = mInflater.inflate(R.layout.vote_item_see, extraContainer, false);
                extraContainer.addView(voteSee);
            }
            voteSee.setVisibility(View.VISIBLE);
            if (voteSubmit != null) {
                voteSubmit.setVisibility(View.GONE);
            }

            voteSee.setBackgroundDrawable(mThemeSettingsHelper.getThemeDrawable(getContext(), R.drawable.vote_see_bg));
            bindVoteSeeView((ViewGroup) voteSee.findViewById(R.id.vote_see_container), data,
                    ((MyGallery) viewparent).inLayout());

        }

        return convertView;
    }

    private void bindVoteSubmitView(ViewGroup container, Map<String, Object> data, boolean inLayout) {
        for (int i = container.getChildCount() - 1; i >= 0; i--) {
            container.getChildAt(i).setVisibility(View.GONE);
        }

        List<Map<String, Object>> itemList = (List<Map<String, Object>>) ModelUtils.getValue(data,
                StringUtil.VOTE_ITEM_LIST);
        if (itemList == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        final int count = itemList.size();
        for (int i = 0; i < count; i++) {
            sb.delete(0, sb.length());
            View itemView = container.getChildAt(i);

            if (itemView == null) {
                itemView = mInflater.inflate(R.layout.vote_submit_item, container, false);
                container.addView(itemView);
                Button b = (Button) itemView.findViewById(R.id.vote_submit_button);
                b.setOnClickListener(mOnClickListener);
            }

            itemView.setVisibility(View.VISIBLE);
            Map<String, Object> itemData = itemList.get(i);
            Button b = (Button) itemView.findViewById(R.id.vote_submit_button);

            b.setTag(R.id.vote_submit, data);
            b.setTag(R.id.vote_submit_button, i);

            sb.append(i + 1).append(".")
                    .append((String) ModelUtils.getValue(itemData, StringUtil.VOTE_ITEM_NAME));
            b.setText(sb.toString());
            
            b.setTextColor(mThemeSettingsHelper.getThemeColor(getContext(), R.color.list_title_color));
            b.setBackgroundDrawable(mThemeSettingsHelper.getThemeDrawable(getContext(), R.drawable.netease_big_button));
        }
    }

    private void bindVoteSeeView(ViewGroup container, Map<String, Object> data, boolean inLayout) {
        for (int i = container.getChildCount() - 1; i >= 0; i--) {
            container.getChildAt(i).setVisibility(View.GONE);
        }

        List<Map<String, Object>> itemList = (List<Map<String, Object>>) ModelUtils.getValue(data,
                StringUtil.VOTE_ITEM_LIST);
        if (itemList == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        final int count = itemList.size();

        int totalNum = Vote.getVoteTotalNum(data);

        int currTotal = 0;
        boolean startSeeAnimation = ModelUtils.getValue(data, "startSeeAnimation") != null;
        for (int i = 0; i < count; i++) {
            sb.delete(0, sb.length());
            View itemView = container.getChildAt(i);

            if (itemView == null) {
                itemView = mInflater.inflate(R.layout.vote_see_item, container, false);
                container.addView(itemView);
            }

            itemView.setVisibility(View.VISIBLE);
            Map<String, Object> itemData = itemList.get(i);

            TextView name = (TextView) itemView.findViewById(R.id.vote_see_item_text);
            ImageView progress = (ImageView) itemView.findViewById(R.id.vote_see_item_progress);
            View progress_p = itemView.findViewById(R.id.vote_see_item_progress_p);
            TextView percnet = (TextView) itemView.findViewById(R.id.vote_see_item_pencent);

            sb.append(i + 1).append(".")
                    .append((String) ModelUtils.getValue(itemData, StringUtil.VOTE_ITEM_NAME));
            name.setText(sb.toString());

            int num;
            if (totalNum == 0) {
                num = 0;
            } else if (i == count - 1) {
                num = 100 - currTotal;
            } else {
                num = Vote.getVoteItemNum(itemData);

                num = (int) (100 * (((float) num) / totalNum) + 0.5f);
                currTotal += num;

            }

            percnet.setText(num + "%");
            progress.setImageResource(getProgressDrawable(i));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) progress.getLayoutParams();
            lp.weight = num;
            progress.setLayoutParams(lp);

            if (startSeeAnimation) {
                progress.startAnimation(AnimationUtils.loadAnimation(getContext(),
                        R.anim.slide_right_in));
            } else {
                progress.clearAnimation();
            }

            View addone = container.findViewById(R.id.addone);
            boolean startAddoneAnimation = ModelUtils.getValue(itemData, "startAddoneAnimation") != null;
            if (startAddoneAnimation) {
                addone.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.addone));
            } else {
                addone.clearAnimation();
            }

            if (inLayout) {
                itemData.remove("startAddoneAnimation");
            }

            lp = (LinearLayout.LayoutParams) progress_p.getLayoutParams();
            lp.weight = 100 - num;
            progress_p.setLayoutParams(lp);
        }

        if (inLayout) {
            data.remove("startSeeAnimation");
        }
    }

    private int getProgressDrawable(int i) {
        if (i > 3) {
            i = i % 4;
        }
        switch (i) {
            case 0:
                return R.drawable.vote_bule;
            case 1:
                return R.drawable.vote_green;
            case 2:
                return R.drawable.vote_red;
            default:
                return R.drawable.vote_yellow;
        }
    }

    public void setViewBinder(VoteViewBinder binder) {
        mViewBinder = binder;
    }
}
